#import "XMSVGAPlayView.h"


@interface XMSVGAPlayView () <SVGAPlayerDelegate>
@property (nonatomic, strong) SVGAPlayer *player;
@property (nonatomic, copy) void (^finishBlock)(SVGAPlayer *player);
@end


@implementation XMSVGAPlayView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubviews];
    }
    return self;
}
#pragma mark - setupSubviews
- (void)setupSubviews {
    [self addSubview:self.player];
}
#pragma mark - Public Methods
- (void)playWithSource:(NSString *)source
           finishBlock:(void (^)(SVGAPlayer *player))finishBlock
            faileBlock:(void (^)(NSError *_Nullable error))faileBlock {
    self.finishBlock = finishBlock;
    SVGAParser *parser = [[SVGAParser alloc] init];
    if ([source hasPrefix:@"http"] || [source hasPrefix:@"https"]) {
        [parser parseWithURL:[NSURL URLWithString:source]
            completionBlock:^(SVGAVideoEntity *_Nullable videoItem) {
                if (videoItem != nil) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.player.videoItem = videoItem;
                        [self.player startAnimation];
                    });
                }
            }
            failureBlock:^(NSError *_Nullable error) {
                if (faileBlock) {
                    faileBlock(error);
                }
            }];
    } else {
        NSString *localPath = [[NSBundle mainBundle] pathForResource:source ofType:@"svga"];
        if (localPath != nil) {
            [parser parseWithData:[NSData dataWithContentsOfFile:localPath]
                cacheKey:source
                completionBlock:^(SVGAVideoEntity *_Nonnull videoItem) {
                    if (videoItem != nil) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            self.player.videoItem = videoItem;
                            [self.player startAnimation];
                        });
                    }
                }
                failureBlock:^(NSError *_Nonnull error) {
                    if (faileBlock) {
                        faileBlock(error);
                    }
                }];
        }
    }
}
#pragma - mark SVGAPlayer Delegate
- (void)svgaPlayerDidAnimatedToPercentage:(CGFloat)percentage {
}
- (void)svgaPlayerDidFinishedAnimation:(SVGAPlayer *)player {
    if (self.finishBlock) {
        self.finishBlock(player);
    }
}
#pragma mark - Getter
- (SVGAPlayer *)player {
    if (_player == nil) {
        _player = [[SVGAPlayer alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _player.delegate = self;
        _player.loops = 1;
        _player.clearsAfterStop = YES;
        _player.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _player;
}
- (void)dealloc {
    [self.player stopAnimation];
    XMLog(@"释放了%@", [self class]);
}
@end
